package com.wgke.bluetooth.ui;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.os.ParcelUuid;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.RecyclerView;

import com.newmobiler.android.ui.adapter.CellAdapter;
import com.newmobiler.android.ui.adapter.OnItemClickListener;
import com.newmobiler.android.ui.adapter.cell.Cell;
import com.newmobiler.android.ui.adapter.cell.DataBinder;
import com.newmobiler.android.ui.adapter.cell.MultiCell;
import com.newmobiler.android.ui.adapter.viewholder.RVViewHolder;
import com.wgke.bluetooth.R;
import com.wgke.bluetooth.event.EventBean;
import com.wgke.bluetooth.event.EventResetBean;
import com.wgke.bluetooth.tools.BlueToothBean;
import com.wgke.bluetooth.utils.CommonUtil;
import com.wgke.bluetooth.utils.ToastUtil;
import com.wgke.bluetooth.vm.HomeVM;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class HomeActivity extends BaseListActivity<HomeVM> {

    private BluetoothAdapter bluetoothAdapter;
    private BluetoothLeScanner bluetoothLeScanner;
    private boolean scanning;

    private static final long SCAN_PERIOD = 10000; // 扫描10秒

    private Map<String, BluetoothDevice> filteredDevices = new HashMap<>();
    private List<BlueToothBean> list = new ArrayList<>();


    @Override
    public int layoutId() {
        return R.layout.activity_home;
    }

    @Override
    public int itemId() {
        return R.layout.item_bluetooth;
    }

    @Override
    public void initOtherView() {
        setEmptyAdapter();
        openBluetoothReceiver = true;
        // 初始化蓝牙适配器
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
        // 检查蓝牙支持
        if (bluetoothAdapter == null) {
            ToastUtil.showMsg("设备不支持蓝牙");
        }
        requestPermissions2(0);
        vm.isShowLoading.observe(this, aBoolean -> findViewById(R.id.loading_layout).setVisibility(aBoolean ? View.VISIBLE : View.INVISIBLE));
        vm.chooseAddress.observe(this, s -> {
            if (TextUtils.isEmpty(s) || filteredDevices.get(s) == null) return;
            Intent intent = new Intent(this, BluetoothConnectActivity.class);
            intent.putExtra("BLUETOOTH_DEVICE", filteredDevices.get(s));
            startActivity(intent);
            vm.chooseAddress.postValue("");
        });

        CellAdapter adapter = CellAdapter.createAdapter(findViewById(R.id.rv));
        Cell cell = MultiCell.convert(R.layout.item_menu, "指令管理", (h, c) -> h.setText(R.id.menuTv, c));
        Cell cell1 = MultiCell.convert(R.layout.item_menu, "解析策略", (h, c) -> h.setText(R.id.menuTv, c));
        adapter.setDataList(List.of(cell, cell1));
        adapter.setOnItemClickListener((h, c) -> {
            if (c == 0) {
                startActivity(new Intent(this, SettingActivity.class));
            } else if (c == 1) {
                startActivity(new Intent(this, PolicyActivity.class));
            }
        });
    }

    @Override
    protected void initStateBar() {
        super.initStateBar();
        Toolbar toolbar = findViewById(R.id.toolbar);
        DrawerLayout dl = findViewById(R.id.drawerLayout);
        toolbar.setNavigationOnClickListener(v -> dl.open());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBean event) {
        vm.isShowLoading.postValue(false);
        if (!CommonUtil.isActivityTop(this)) return;
        if (event.status == 1) {
            vm.chooseAddress.postValue(event.device.getAddress());
        } else {
            ToastUtil.showMsg("连接失败");
        }
    }

    @SuppressLint("MissingPermission")
    @Override
    public void nextStep(int i) {
        Log.e("HomeActivity", "nextStep: " + i);
        if (i == 1 || !isOpenBluetooth(bluetoothAdapter)) return;
        isOpenBluetooth = true;
        postDelayed(2000, this::startRefresh);
        onRefresh();
    }

    @Override
    public void onRefresh() {
        Log.e("HomeActivity", "onRefresh:");
        if (!isOpenBluetooth) {
            postDelayed(1000, this::finishRefresh);
            return;
        }
        postDelayed(1000 * 7, () -> {
            scanLeDevice(false);
            finishRefresh();
        });
        scanLeDevice(true);
    }

    private void changeData(BlueToothBean bean) {
        if (TextUtils.isEmpty(bean.getName())) return;
        for (BlueToothBean blueToothBean : list) {
            if (blueToothBean.getAddress().equals(bean.getAddress())) return;
        }
        if (list.isEmpty()) clear();
        list.add(bean);
        addCell(bean, this::setDataItem);
    }

    @Override
    public void emptyAgain() {
        requestPermissions2(0);
    }

    private int[] resColor = new int[]{R.color.purple_200, R.color.purple_500, R.color.purple_700, R.color.teal_200, R.color.teal_700};

    private String address;

    private void setDataItem(RVViewHolder holder, BlueToothBean bean) {
        ((CardView) holder.getView(R.id.cView)).setCardBackgroundColor(ContextCompat.getColor(this, resColor[holder.getAdapterPosition() % resColor.length]));
        holder.setText(R.id.title, bean.getName());
        holder.setText(R.id.content, bean.getAddress() + "\n" + bean.typeToString() + "  -   " + bean.rssiToString());
        holder.setOnClickListener(R.id.connect, v -> {
            address = bean.getAddress();
            connectDevice(address);
        });
    }

    private void connectDevice(String address) {
        BluetoothDevice device = filteredDevices.get(address);
        if (device == null) {
            ToastUtil.showMsg("设备失效，请重新刷新");
            return;
        }
        vm.connectDevice(device);
    }


    @SuppressLint("MissingPermission")
    private void scanLeDevice(boolean enable) {
        if (enable) {
            // 停止之前的扫描
            postDelayed(SCAN_PERIOD, () -> {
                scanning = false;
                bluetoothLeScanner.stopScan(leScanCallback);
            });
            scanning = true;
            filteredDevices.clear();
            list.clear();
            // 设置扫描过滤器 - 只显示有服务的设备
            ScanFilter filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString("0000110A-0000-1000-8000-00805F9B34FB")) // 示例服务UUID
                    .build();

            ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
            //bluetoothLeScanner.startScan(Arrays.asList(filter), settings, leScanCallback);
            bluetoothLeScanner.startScan(leScanCallback);
        } else {
            scanning = false;
            bluetoothLeScanner.stopScan(leScanCallback);
        }
    }

    private ScanCallback leScanCallback = new ScanCallback() {
        @SuppressLint("MissingPermission")
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            BluetoothDevice device = result.getDevice();

            if (filteredDevices.get(device.getAddress()) == null) {
                filteredDevices.put(device.getAddress(), device);
                BlueToothBean bean = BlueToothBean.get(device.getName(), device.getAddress());
                bean.setType("" + device.getType());
                bean.setStatus("" + device.getBondState());
                bean.setRssi(result.getRssi());
                bean.setMajorDeviceClass(device.getBluetoothClass().getMajorDeviceClass());
                changeData(bean);
                Log.w("HomeActivity", "find device: " + device.getName() + " " + device.getAddress() + " " + bean.toMajorDeviceClassString() + " " + bean.getMajorDeviceClass() + ";" + device.getBluetoothClass().getDeviceClass());
            } else {
                //Log.w("HomeActivity", "发现设备: " + device.getName() + " " + device.getAddress());
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            ToastUtil.showMsg("扫描失败");
        }
    };



}
